local joy__zecai = fk.CreateSkill {

  name = "joy__zecai",

  tags = { Skill.Limited, },

}



joy__zecai:addEffect(fk.RoundEnd, {
  name = "joy__zecai",
  frequency = Skill.Limited,
  events = {fk.RoundEnd},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(joy__zecai.name) and player:usedSkillTimes(joy__zecai.name, Player.HistoryGame) < 1
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local player_table = {}
    room.logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
      local use = e.data[1]
      if use.card.type == Card.TypeTrick then
        local from = use.from
        player_table[from] = (player_table[from] or 0) + 1
      end
    end, Player.HistoryRound)
    local max_time, max_pid = 0, nil
    for pid, time in pairs(player_table) do
      if time > max_time then
        max_pid, max_time = pid, time
      elseif time == max_time then
        max_pid = 0
      end
    end
    local max_p = nil
    if max_pid ~= 0 then
      max_p = room:getPlayerById(max_pid)
    end
    if max_p and not max_p.dead then
      room:setPlayerMark(max_p, "@@joy__zecai_extra", 1)
    end
    local to = room:askForChoosePlayers(player, table.map(room.alive_players,Util.IdMapper), 1, 1, "#joy__zecai-choose", joy__zecai.name, true)
    if max_p and not max_p.dead then
      room:setPlayerMark(max_p, "@@joy__zecai_extra", 0)
    end
    if #to > 0 then
      event:setCostData(self, {to[1], max_pid})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tar = room:getPlayerById(event:getCostData(self)[1])
    if not tar:hasSkill("joyex__jizhi", true) then
      room:addPlayerMark(tar, "joy__zecai_tmpjizhi")
      room:handleAddLoseSkills(tar, "joyex__jizhi", nil, true, false)
    end
    if event:getCostData(self)[1] == event:getCostData(self)[2] then
      tar:gainAnExtraTurn()
    end
  end,
})
joy__zecai:addEffect(fk.RoundEnd, {
  refresh_events = {fk.RoundEnd},
  can_refresh = function(self, event, target, player, data)
    return player:getMark("joy__zecai_tmpjizhi") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:handleAddLoseSkills(player, "-joyex__jizhi", nil, true, false)
  end,
})

return joy__zecai